<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试拖动水平条</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            position: relative;
            margin: 50px auto;
            width: 400px;
            height: 10px;
            background-color: green;
        }

        .box>.over {
            position: absolute;
            top: -5px;
            left: 0;
            width: 10px;
            height: 20px;
            background-color: red;
            cursor: pointer;
        }

        .box>.cover {
            position: absolute;
            top: 0;
            left: 0;
            /* width: 400px; */
            height: 10px;
            background-color: red;
        }

        p {
            text-align: center;
            color: red;
            font-size: 20px;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="over"></div>
        <div class="cover"></div>
    </div>
    <p>加载中...</p>
</body>
<script>
    var box = document.querySelector('.box')
    var over = document.querySelector('.over')
    var cover = document.querySelector('.cover')
    var p = document.querySelector('p')
    //鼠标按下事件
    over.onmousedown = function (event) {
        var e = event || window.event
        var overLeft = this.offsetLeft
        var initLeft = e.clientX
        // 鼠标移动事件
        document.onmousemove = function (event) {
            var e = event || window.event
            var moveX = e.clientX - initLeft + overLeft
            if (moveX > box.offsetWidth - over.offsetWidth) {
                moveX = box.offsetWidth - over.offsetWidth
            } else if (moveX < 0) {
                moveX = 0
            }
            cover.style.width = moveX + 'px'
            over.style.left = moveX + 'px'
            var percent = ((moveX / (box.offsetWidth - over.offsetWidth)) * 100).toFixed(2) + '%'
            // 拖动过程不选中文本
            window.getSelection() ? window.getSelection().removeAllRanges() : document.selection.empty();
            p.innerHTML = '加载中...' + percent;
        }
        // 鼠标松开事件
        document.onmouseup = function () {
            // 鼠标移动事件清除
            document.onmousemove = ""
        }
    }
</script>

</html>